﻿#include "Config.h"
#include <QJsonDocument>
#include <QCoreApplication>
#include <QFile>
#include "config_keys.h"
#include "Logger.h"

namespace {
const QString kConfigFileName = "bsConfig.json";
} // namespace

bool Configger::init()
{
    if (_initialized) {
        return true;
    }
    const QString path = QCoreApplication::applicationDirPath() + "/" + kConfigFileName;
    QFile file(path);

    if (file.exists()) {
        if (!file.open(QIODevice::ReadOnly)) {
            CERROR() << "Failed to open config file.";
            return false;
        }

        QByteArray data = file.readAll();
        file.close();

        QJsonParseError error;
        QJsonDocument doc = QJsonDocument::fromJson(data, &error);
        if (error.error != QJsonParseError::NoError) {
            CERROR() << "Failed to parse config file:" << error.errorString();
            return false;
        }

        _configData = doc.object();
    } else {
        _configData.insert(config_keys::Language, config_lang_value::Chinese);
        _configData.insert(config_keys::Style, config_style_value::Light);

        if (!save()) {
            CERROR() << "Failed to save default config.";
            return false;
        }
    }

    _initialized = true;
    return true;
}

QVariant Configger::get(const QString& key, const QVariant& defaultValue)
{
    return _configData.contains(key) ? _configData.value(key).toVariant() : defaultValue;
}

void Configger::set(const QString& key, const QVariant& value)
{
    _configData.insert(key, QJsonValue::fromVariant(value));
}

void Configger::remove(const QString& key) { _configData.remove(key); }

bool Configger::save()
{
    const QString path = QCoreApplication::applicationDirPath() + "/" + kConfigFileName;
    QFile file(path);
    if (!file.open(QIODevice::WriteOnly)) {
        qWarning() << "Failed to write config file.";
        return false;
    }

    QJsonDocument doc(_configData);
    file.write(doc.toJson(QJsonDocument::Indented));
    file.close();
    return true;
}
